
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic

from .models import Choice, Question
# def index(request):
#     latest_question_list = Question.objects.order_by('-pub_date')[:5]
#     context = {'latest_question_list': latest_question_list}
#     return render(request, 'polls/index.html', context)

# def detail(request, question_id):
#     question = get_object_or_404(Question, pk=question_id)
#     return render(request, 'polls/detail.html', {'question': question})

# def results(request, question_id):
#     response = "You're looking at the results of question %s."
#     return HttpResponse(response % question_id)


class IndexView(generic.ListView):
    # 定义模板名称
    template_name = 'polls/index.html'
    # 定义上下文对象名称
    context_object_name = 'latest_question_list'

    def get_queryset(self):
        """Return the last five published questions."""
        # 返回最后五个发布的问题
        return Question.objects.order_by('-pub_date')[:5]


class DetailView(generic.DetailView):
    # 定义模型
    model = Question
    # 定义模板名称
    template_name = 'polls/detail.html'


class ResultsView(generic.DetailView):
    # 定义模型
    model = Question
    # 定义模板名称
    template_name = 'polls/results.html'

#@login_required(login_url='/accounts/login/')：需要登录才能访问
#@permission_required(perm='polls.vote_poll', login_url='/accounts/login/')：需要具有投票权限才能访问
def vote(request, question_id):
    # 获取问题对象
    question = get_object_or_404(Question, pk=question_id)
    try:
        # 获取用户提交的投票选择
        selected_choice = question.choice_set.get(pk=request.POST['choice'])
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        # 如果没有选择投票选择，则重新显示投票表单
        return render(request, 'polls/detail.html', {
            'question': question,
            'error_message': "You didn't select a choice.",
        })
    else:
        # 如果有选择投票选择，则投票数量加1，并保存
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        # 总是返回一个HttpResponseRedirect，以防止用户点击回退按钮时再次提交表单
        return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))

def results(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    return render(request, 'polls/results.html', {'question': question})